////////////////////////////////////////////////////////////////////////////////
//
// Licensed under the MIT License
//
// Copyright (c) 2008 Chris Colinsky
// All Rights Reserved
//
// version	0.4
// http://code.google.com/p/sugarcookie/
// http://code.google.com/p/sugarcookie/wiki/License
//
////////////////////////////////////////////////////////////////////////////////

import sugarcookie.events.EventController;
import sugarcookie.events.*;
import sugarcookie.logger.Logger;
import sugarcookie.file.FileLoader;

import flash.display.BitmapData;

class sugarcookie.ui.BitmapDataManager extends EventController {
	private static var _instance:BitmapDataManager = null;
	private var _log:Logger;
	private var _loader:FileLoader;
	private var _bmdCollection:Array;
	private var _images:MovieClip;
	
	private function BitmapDataManager() {
		super(this);
		_log = Logger.getLog();
		_loader = new FileLoader();
		_loader.addEventListener("onLoadInit",this);
		_loader.addEventListener("onProgress",this);
		
		_images = _level0.createEmptyMovieClip("_bmdImgHolder",_level0.getNextHighestDepth());
		_images._visible = false;
		_bmdCollection = [];
	}
	
	public static function getInst():BitmapDataManager {
		return BitmapDataManager(_instance?_instance:_instance = new BitmapDataManager());
	}
	
	public function addToCacheQue(_id:String,u:String):Void {
		if (_bmdCollection[_id]) return;
		
		_bmdCollection[_id] = {_status:false,_bmd:{},url:u};
		_loader.addFileToQue(_images.createEmptyMovieClip(_id,_images.getNextHighestDepth()),u);
	}
	
	public function initQue():Void {
		if (!_loader.isLoading) _loader.initFileQue(false);	
	}
	
	public function getImageBitmap(_id:String):BitmapData {
		if (_bmdCollection[_id]._status) return _bmdCollection[_id]._bmd;
		else return null;
	}
	
	private function onLoadInit(evt:Event):Void {
		if (evt.status) {
			_loader.clearFileQue();
			
			var loadedImgs:Array = [];
			for (var i:String in _bmdCollection) {
				if (!_bmdCollection[i]._status) {
					loadedImgs.push(i);
					setBmdData(i);
				}
			}
			_loader.clearFileQue();
			postEvent("onLoadInit","BitmapData",evt.status,true,loadedImgs);
		}
	}
	
	private function onProgress(evt:Event):Void {
		postEvent("onProgress",null,false,false,evt.data);
	}
	
	private function setBmdData(_id:String):Void {
		var bmd:BitmapData = new BitmapData(_images[_id]._width, _images[_id]._height);
		bmd.draw(_images[_id]);
		_bmdCollection[_id]._bmd = bmd;
		_bmdCollection[_id]._status = true;
	}
}